﻿//Copyright 2011 - Jonathan Allen

using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
using System.Diagnostics.Contracts;

namespace Granite.Xaml.Converters
{
    /// <summary>
    /// Use this converter to hide a control when the bound value is null or an empty string.
    /// For WPF, the parameter is used to choose between Collapsed and Hidden. The default is Collapsed.
    /// </summary>
	[ValueConversion(typeof(object), typeof(bool))]
	public class NotNullToVisibleConverter : OneWayMarkupValueConverter<NotNullToVisibleConverter>
    {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType">Visibility</param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
        [Pure]
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            CheckTargetType(targetType, typeof(Visibility), typeof(Visibility?));
            CheckParameterType(parameter, typeof(Visibility), typeof(string));

            var newVisibility = Visibility.Collapsed;

#if !SILVERLIGHT
            if (parameter is Visibility)
                newVisibility = (Visibility)parameter;
            else
            {
                var stringParameter = parameter as String;
                if (stringParameter != null && stringParameter.ToUpperInvariant() == "HIDDEN")
                    newVisibility = Visibility.Hidden;
            }
#endif

            if (value == null)
                return newVisibility;

#if !WINDOWS_PHONE
            if (value is String && String.IsNullOrWhiteSpace((string)value))
                return newVisibility;
#else
            if (value is String && Granite.StringUtilities.IsNullOrWhiteSpace((string)value))
                return newVisibility;
#endif

            return Visibility.Visible;
        }

    }
}
